import Vue from 'vue'
import axios from 'axios'
import App from './App.vue'
import router from './router'
import store from './store'
import Api from '@/api';
import defaultAvatar from './assets/images/unknown_contact_avatar.png';
import config from '@/config'
import { formatTime } from '@/lib/utils'
import preview from 'vue-photo-preview'
import 'vue-photo-preview/dist/skin.css'
import VModal from 'vue-js-modal'
import contextmenu from '@/lib/contextmenu'

import ElementUI from 'element-ui';
import 'element-ui/lib/theme-chalk/index.css';
Vue.use(ElementUI);

Vue.use(VModal)
Vue.use(preview)
Vue.use(contextmenu)
// export const EventBus = new Vue();
const ajax = axios.create({
  baseURL: config.apiUrl,
  timeout: 1000000,
  withCredentials: true,
})

ajax.interceptors.response.use(function(response){
  if (response.status == 200) {
    if(response.data.code === 501){
      sessionStorage.removeItem( btoa(config.kf_key) )
      store.dispatch('destroyWebSocket')
      store.commit('updateUIState',{ adminid:-1 })
      return Promise.reject(response.data.message)
    }else{
      return response.data
    }
    
  } else {
    return Promise.reject(response.statusText)
  }
}, function(error){
  return Promise.reject(error);
})
layui.use(['element', 'form', 'layer'], function(){
  const element = layui.element;
  const form = layui.form;
  Vue.prototype.$element = element;
  Vue.prototype.$form = form;
  Vue.prototype.$layer = layer;
  Vue.prototype.$msg = layui.layer.msg;
  // Vue.prototype.$confirm = layui.layer.confirm;
})
Vue.prototype.uploadFile = function (file, options) {
  return new Promise((resolve, reject)=>{
    const { type: fileType } = file
    const type = /image/.test(fileType) ? 1 : /video/.test(fileType) ? 3 : 2
    const form = new FormData()
    form.append("mFile", file)
    form.append("type", type)
    ajax.post("/upload/upload", form, options).then(data=>{
      resolve(data.resultPath)
    }).catch(e=>reject(e))
  })
}
Vue.prototype.$get = ajax.get
Vue.prototype.$post = ajax.post
Vue.prototype.defaultAvatar = defaultAvatar
Vue.prototype.formatTime = formatTime
Vue.prototype.transUserData = data => {
  if (Array.isArray(data)) {
    return data.map( item => {
      return {
        name: item.friendnick || item.nick,
        avatar: item.friendavatar || '',
        wxid: item.friendwxid || '',
        type: item.msgtype || 'user',
        lastMessage: item.pushcontent,
        mark: item.friendremark || '',
        decline: item.showstatus ? false : true,
        gender:item.sex,
        ...item
      }
    })
  } else {
     return {
      name: data.friendnick || item.nick,
      avatar: data.friendavatar || data.avatar || '',
      wxid: data.friendwxid || '',
      type: data.msgtype || 'user',
      lastMessage: data.pushcontent,
      mark: data.friendremark || '',
      decline: data.showstatus ? false : true,
      gender:item.sex,
      ...data
    }
  }
}
Vue.prototype.transGroupData = data => {
  if (Array.isArray(data)) {
    return data.map( item => {
      return {
        name: item.groupname || '聊天群',
        avatar: item.groupavatar || item.avatar || item.flags || '',
        wxid: item.id || '',
        type: 'group',
        manager: item.flags && item.flags.isFirst == 1,
        memberCount: item.personNum || 0,
        friendsCount: 0,
        mark: item.description || '',
        always_top: item.isfirst ? true : false,
        decline: item.showstatus ? false : true,
        ...item
      }
    })
  } else {
    return {
      name: data.groupname || '聊天群',
      avatar: data.groupavatar || data.avatar || data.flags || '',
      wxid: data.id || '',
      type: 'group',
      manager: data.flags && data.flags.isFirst == 1,
      memberCount: data.personNum || 0,
      friendsCount: 0,
      mark: data.description || '',
      always_top: data.isfirst ? true : false,
      decline: data.showstatus ? false : true,
      ...data
    }
  }
}
Vue.prototype.isObject = (data)=>{
  return Object.prototype.toString.call(data)=='[object Object]'
}
Vue.prototype.getServicesFriends = function (services) {
  let friends = []
  const getFriends = services.map(s=>{
    return this.$api.friend.list({
      csid: s.csid,
      wxaccount: s.wxid
    })
  })
  return Promise.all(getFriends).then(data=>{
    let flatData = []
    data.map(d=>{
      flatData = [...flatData, ...d]
    })
    flatData.map(f=>{
      const sameFriend = friends.filter(friend=>friend.friendwxid == f.friendwxid).length
      if (!sameFriend) {
        friends.push(f)
      }
    })
    return this.transUserData(friends)
  })
}
Vue.prototype.getServicesGroups = function (services) {
  let groups = []
  const getGroups = services.map(s=>{
    return this.$api.group.list({
      csid: s.csid,
      wxaccount: s.wxid
    })
  })
  return Promise.all(getGroups).then(data=>{
    let flatData = []
    data.map(d=>{
      flatData = [...flatData, ...d]
    })
    flatData.map(f=>{
      const sameFriend = groups.filter(group=>group.id == f.id).length
      if (!sameFriend) {
        groups.push(f)
      }
    })
    return this.transGroupData(groups)
  })
}
Vue.prototype.config = config
Vue.config.productionTip = false

Vue.use(Api)

new Vue({
  router,
  store,
  render: h => h(App)
}).$mount('#app')
